package com.qujia.web.controller.system;

import java.util.*;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.qujia.common.core.domain.TreeSelect;
import com.qujia.common.core.domain.model.LoginUser;
import com.qujia.station.domain.DeptInfoDemo;
import com.qujia.system.domain.SysDeptFalge;
import com.qujia.system.domain.SysRespon;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.qujia.common.annotation.Log;
import com.qujia.common.constant.UserConstants;
import com.qujia.common.core.controller.BaseController;
import com.qujia.common.core.domain.AjaxResult;
import com.qujia.common.core.domain.entity.SysDept;
import com.qujia.common.enums.BusinessType;
import com.qujia.common.utils.SecurityUtils;
import com.qujia.common.utils.StringUtils;
import com.qujia.system.service.ISysDeptService;

/**
 * 部门信息
 *
 * @author qujia
 */
@RestController
@RequestMapping("/system/dept")
public class SysDeptController extends BaseController
{
    @Autowired
    private ISysDeptService deptService;

    /**
     * 获取部门列表
     */
    @GetMapping("/list")
    public AjaxResult list(SysDept dept)
    {
        List<SysDept> depts = deptService.selectDeptList(dept);
        return AjaxResult.success(depts);
    }

    @GetMapping("/listTree")
    public AjaxResult listTree(SysDept dept)
    {
        List<SysDept> depts = deptService.selectDeptListTree(dept);
        return AjaxResult.success(depts);
    }
    /**
     * 根据当前人员信息返回不同的部门信息
     */
    @GetMapping("/selectDeptFlage")
    public AjaxResult selectDeptFlage()
    {
        LoginUser currentUser = SecurityUtils.getLoginUser();
        SysDeptFalge sysDeptFalge=new SysDeptFalge();
        SysDept nowSysDept=deptService.selectDeptById(currentUser.getUser().getDeptId());
        if(nowSysDept.getParentId()==0){
            return AjaxResult.success(sysDeptFalge);
        }
        if(nowSysDept.getParentId()==100){
            sysDeptFalge.setGroupDept(nowSysDept);
            return AjaxResult.success(sysDeptFalge);
        }
        sysDeptFalge.setGroupDept(deptService.selectDeptById(nowSysDept.getParentId()));
        sysDeptFalge.setUserDept(nowSysDept);
        return AjaxResult.success(sysDeptFalge);
    }

    /**
     * 查询部门列表（排除节点）
     */
    @GetMapping("/list/exclude/{deptId}")
    public AjaxResult excludeChild(@PathVariable(value = "deptId", required = false) Long deptId)
    {
        List<SysDept> depts = deptService.selectDeptList(new SysDept());
        Iterator<SysDept> it = depts.iterator();
        while (it.hasNext())
        {
            SysDept d = (SysDept) it.next();
            if (d.getDeptId().intValue() == deptId
                    || ArrayUtils.contains(StringUtils.split(d.getAncestors(), ","), deptId + ""))
            {
                it.remove();
            }
        }
        return AjaxResult.success(depts);
    }

    /**
     * 根据部门编号获取详细信息
     */
    @GetMapping(value = "/{deptId}")
    public AjaxResult getInfo(@PathVariable Long deptId)
    {
        return AjaxResult.success(deptService.selectDeptById(deptId));
    }

    @GetMapping(value = "/getGroupInfo")
    public AjaxResult getGroupInfo(SysDept dept)
    {
        SysDept sysDepts =new SysDept();
        LoginUser currentUser = SecurityUtils.getLoginUser();
        SysDept  sysDept=deptService.selectDeptById(currentUser.getUser().getDeptId());
        if(sysDept.getJiBie()!=null && sysDept.getJiBie()==1){
            dept.setDeptId(sysDept.getDeptId());
            sysDepts=deptService.getGroupInfo(dept);
        }else if(sysDept.getJiBie()!=null && sysDept.getJiBie()==2){
            dept.setDeptId(sysDept.getParentId());
            sysDepts=deptService.getGroupInfo(dept);
        }else{
            sysDepts=new SysDept();
        }
//        SysDeptDemo sysDeptDemo =new SysDeptDemo();
//        BeanUtils.copyProperties(sysDeptDemo, sysDepts);
        return AjaxResult.success(sysDepts);
    }
    /**获取当前登录人的站点信息*/
    @GetMapping(value = "/getGroupByUser")
    public AjaxResult getGroupByUser()
    {

        LoginUser currentUser = SecurityUtils.getLoginUser();
        SysDept sysDept=deptService.selectDeptById(currentUser.getUser().getDeptId());
        if(sysDept.getParentId()==0||sysDept.getParentId()==100){
            return AjaxResult.success(sysDept);
        }
        SysDept sysDept1=deptService.selectDeptById(sysDept.getParentId());
        return AjaxResult.success(sysDept1);
    }

    /**
     * 获取部门下拉树列表
     */
    @GetMapping("/treeselect")
    public AjaxResult treeselect(SysDept dept)
    {
        List<SysDept> depts = deptService.selectDeptList(dept);
        return AjaxResult.success(deptService.buildDeptTreeSelect(depts));
    }

    /**
     * 获取部门下拉树列表
     */
    @GetMapping("/userdepttree")
    public AjaxResult userdepttree(SysDept dept)
    {
        LoginUser currentUser = SecurityUtils.getLoginUser();
        //获取当前登陆人级别
        SysDept deptJb=deptService.selectDeptById(currentUser.getUser().getDeptId());
        List<SysDept> depts =new ArrayList<>();
        if(deptJb!=null ){
            if(deptJb.getJiBie()==0){
                dept.setDeptId(null);
                depts = deptService.selectDeptList(dept);
            }else if(deptJb.getJiBie()==1){
                dept.setParentId(deptJb.getDeptId());
                dept.setDeptId(deptJb.getDeptId());
                depts= deptService.queryDeptList(dept);
            }else if(deptJb.getJiBie()==2){
                dept.setDeptId(deptJb.getDeptId());
                depts= deptService.selectDeptList(dept);
            }
        }
        List<TreeSelect> list = deptService.buildDeptTreeSelect(depts);
        return AjaxResult.success(list);
    }
    /**
     * 查询所有的集团
     *
     */
    @GetMapping("/groupList")
    public AjaxResult groupList(SysDept dept)
    {
        LoginUser currentUser = SecurityUtils.getLoginUser();
        List<SysDept> depts =new ArrayList<>();
        if(currentUser.getUser().getDept().getJiBie() !=null && currentUser.getUser().getDept().getJiBie()== 0 && currentUser.getUser().getAgentFlag().equals("1")){
            SysDept sysDept =new SysDept();
            sysDept.setUserId(currentUser.getUser().getUserId());
            //查询代理人所有的集团
            depts = deptService.selectGroupAgentList(sysDept);
        }else {
            SysDept sysDept =new SysDept();
            sysDept.setParentId(currentUser.getUser().getDeptId());
            depts = deptService.searchDeptList(sysDept);
        }
        return AjaxResult.success(depts);
    }
    /**
     * 查询当前登陆是是否是lng集团下的
     *
     */
    @GetMapping("/isLngInfoList")
    public AjaxResult isLngInfoList(){
         boolean  flag = deptService.isLngInfoList();
        return AjaxResult.success(flag);
    }
    /**
     * 根据集团查询油站信息
     *
     */
    @GetMapping("/searchDeptList")
    public AjaxResult searchDeptList(SysDept dept)
    {
        LoginUser currentUser = SecurityUtils.getLoginUser();
        List<SysDept> depts = new ArrayList<>();
        if(dept!=null&& dept.getDeptId()!=null ){
            SysDept sysDept =new SysDept();
            sysDept.setParentId(dept.getDeptId());
            depts = deptService.searchDeptList(sysDept);
        }else{
            if(currentUser.getUser().getDept().getJiBie()!=null && currentUser.getUser().getDept().getJiBie()==1){
                SysDept sysDept =new SysDept();
                sysDept.setParentId(currentUser.getUser().getDeptId());
                depts = deptService.searchDeptList(sysDept);
            }
        }
        return AjaxResult.success(depts);
    }

    /****
     * 查询分配代理管理
     */
    @GetMapping("/selectSysAgentList")
    public AjaxResult selectSysAgentList(SysDept dept)
    {
        List<SysDept> depts = deptService.selectSysAgentList(dept);
        List<DeptInfoDemo> deptList=new ArrayList<>();
        if(depts!=null && depts.size()>0){
            for(SysDept sysDept :depts){
                DeptInfoDemo deptDemo =new DeptInfoDemo();
                deptDemo.setDeptId(sysDept.getDeptId());
                deptDemo.setDeptName(sysDept.getDeptName());
                deptList.add(deptDemo);
            }
        }
        return AjaxResult.success(deptList);
    }

    @GetMapping("/selectDeptBalance")
    public AjaxResult selectDeptBalance(SysDept dept)
    {
        LoginUser currentUser = SecurityUtils.getLoginUser();
        SysDept deptInfo = deptService.selectDeptById(currentUser.getUser().getDeptId());
        DeptInfoDemo deptDemo =new DeptInfoDemo();
        if(deptInfo!=null&&deptInfo.getJiBie()!=null && deptInfo.getJiBie() == 2){
            deptDemo.setDeptId(deptInfo.getDeptId());
            deptDemo.setBalance(deptInfo.getBalance());
            deptDemo.setDeptName(deptInfo.getDeptName());
        }
        return AjaxResult.success(deptDemo);
    }

    /**
     * 加载对应角色部门列表树
     */
    @GetMapping(value = "/roleDeptTreeselect/{roleId}")
    public AjaxResult roleDeptTreeselect(@PathVariable("roleId") Long roleId)
    {
        List<SysDept> depts = deptService.selectDeptList(new SysDept());
        AjaxResult ajax = AjaxResult.success();
        ajax.put("checkedKeys", deptService.selectDeptListByRoleId(roleId));
        ajax.put("depts", deptService.buildDeptTreeSelect(depts));
        return ajax;
    }

    /**
     * 新增部门
     */
    @Log(title = "部门管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysDept dept)
    {
        if (UserConstants.NOT_UNIQUE.equals(deptService.checkDeptNameUnique(dept)))
        {
            return AjaxResult.error("新增部门'" + dept.getDeptName() + "'失败，部门名称已存在");
        }
        dept.setCreateBy(SecurityUtils.getUsername());
        return toAjax(deptService.insertDept(dept));
    }

    /**
     * 修改部门
     */
    @Log(title = "部门管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysDept dept)
    {
        if (UserConstants.NOT_UNIQUE.equals(deptService.checkDeptNameUnique(dept)))
        {
            return AjaxResult.error("修改部门'" + dept.getDeptName() + "'失败，部门名称已存在");
        }
        else if (dept.getParentId().equals(dept.getDeptId()))
        {
            return AjaxResult.error("修改部门'" + dept.getDeptName() + "'失败，上级部门不能是自己");
        }
        else if (StringUtils.equals(UserConstants.DEPT_DISABLE, dept.getStatus())
                && deptService.selectNormalChildrenDeptById(dept.getDeptId()) > 0)
        {
            return AjaxResult.error("该部门包含未停用的子部门！");
        }

        if("1".equals(dept.getMnoStatus())) {
            if(dept.getMnoArray()==null){
                return AjaxResult.error("未传入分账账户信息");
            }
            SysDept dept1=deptService.selectDeptById(dept.getDeptId());
            if (dept.getMnoArray().equals(dept1.getMnoArray())){
              //分款账户没有发生变化，不需要重新调用接口
            }else {
                try {

                    SysRespon respon1=QuerySign(dept);
                    if ("02".equals(respon1.getResponMessage())) {
                        SysRespon respon=setMnoArray(dept);
                        if (!"0000".equals(respon.getResponCode())) {
                            return AjaxResult.error(respon.getResponMessage());
                        }
                    } else if("00".equals(respon1.getResponMessage())) {
                        return AjaxResult.error("已发送链接，未签约");
                    }else  if("01".equals(respon1.getResponMessage())){
                        return AjaxResult.error("签约失败");
                    }else if("03".equals(respon1.getResponMessage())){
                        return AjaxResult.error("未签约");
                    }else {
                        return AjaxResult.error(respon1.getResponMessage());
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        dept.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(deptService.updateDept(dept));
    }
    /**
     * 设置分账模式
     */

    @GetMapping("/mnoSplit/{deptId}")
    public AjaxResult mnoSplit(@PathVariable Long deptId)
    {
       if(deptId ==null){
           return AjaxResult.error("传入id参数错误");
       }
       SysDept dept1=deptService.selectDeptById(deptId);
       if(dept1.getDeptId()==null){
           return AjaxResult.error("未查询到对应的信息");
       }
        try {
            // QuerySign(dept);
            SysRespon respon=SetMnoSign(dept1);
            if (!"0000".equals(respon.getResponCode())){
                return AjaxResult.error(respon.getResponMessage());
            }else {
            return AjaxResult.success(respon.getResponMessage());
            }
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("调用接口失败"+e.getMessage());
        }
    }

    /**
     * 删除部门
     */
    @Log(title = "部门管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{deptId}")
    public AjaxResult remove(@PathVariable Long deptId)
    {
        if (deptService.hasChildByDeptId(deptId))
        {
            return AjaxResult.error("存在下级部门,不允许删除");
        }
        if (deptService.checkDeptExistUser(deptId))
        {
            return AjaxResult.error("部门存在用户,不允许删除");
        }
        return toAjax(deptService.deleteDeptById(deptId));
    }


    @Log(title = "部门管理", businessType = BusinessType.UPDATE)
    @PutMapping("/updateDeptInfo")
    public AjaxResult updateDeptInfo(@RequestBody SysDept dept)
    {
        int i=0;
        if(dept!=null && dept.getDeptId()!=null){
            dept.setUpdateBy(SecurityUtils.getUsername());
            i = deptService.updateDept(dept);
        }else {
            return  AjaxResult.error("站点id 不能为空");
        }
        return toAjax(i);
    }

    public SysRespon SetMnoSign( SysDept dept) throws Exception {

        SysRespon respon=new SysRespon();
        JSONObject reqData = new JSONObject();
        reqData.put("mno",dept.getMno() );
        reqData.put("signType", "00");
        String req= SXFPaySign.getSXFPay(reqData);
        ///logger.debug("参数信息："+req);
        System.out.println("req:" + req);
        //此处不要改变reqData里面值的顺序用LinkedHashMap
        HashMap reqMap = JSON.parseObject(req, LinkedHashMap.class, Feature.OrderedField);
        //组装加密串
        String signContent = RSASignature.getOrderContent(reqMap);
        System.out.println("拼接后的参数：" + signContent);
        //logger.debug("拼接后的参数："+signContent);
        //sign
        String sign = RSASignature.encryptBASE64(RSASignature.sign(signContent, SXFPaySign.privateKey));
        System.out.println("============签名:" + sign);
        reqMap.put("sign", sign);
        String reqStr = JSON.toJSONString(reqMap);
        System.out.println("请求参数:" + reqMap);
        System.out.println("请求参数:" + reqStr);
        //调用第三方接口地址
        String url = "https://openapi.suixingpay.com/merchant/sign/getUrl";//生产地址
        String resultJson = HttpUtils.connectPostUrl(url, reqStr);
        System.out.println("返回信息：" + resultJson);
        //不要对reqData排序 所以用LinkedHashMap
        HashMap<String, Object> result = JSON.parseObject(resultJson, LinkedHashMap.class, Feature.OrderedField);
        if ("0000".equals(result.get("code"))) {
            //验签
            String signResult = result.get("sign").toString();
            result.remove("sign");
            String resultStr = RSASignature.getOrderContent(result);
            System.out.println("resultStr: " + resultStr);
            //sign
            String resultSign = RSASignature.encryptBASE64(RSASignature.sign(signContent, SXFPaySign.privateKey));
            System.out.println("resultSign: " + resultSign);
            //组装加密串
            if (RSASignature.doCheck(resultStr, signResult, SXFPaySign.sxfPublic)) {
                System.out.println("===================验签成功==============");
                //
                if(result.containsKey("respData")){
                    HashMap<String, Object> result1 = JSON.parseObject(result.get("respData")+"", LinkedHashMap.class, Feature.OrderedField);
                    if("0000".equals(result1.get("bizCode"))){
                        respon.setResponCode("0000");
                        System.out.println(result1.get("retUrl"));
                        String url1=result1.get("retUrl")+"";
                        respon.setResponMessage(result1.get("retUrl")+"");
                        return respon;
                    }else {
                        respon.setResponCode(result1.get("bizCode") + "");
                        respon.setResponMessage(result1.get("bizMsg") + "");
                    }
                    //判断 bizCode bizCode =="0000" 则业务成功
                }else {
                    respon.setResponCode("0004");
                    respon.setResponMessage(result.get("msg") + "");
                }
            }else {
                respon.setResponCode("0002");
                respon.setResponMessage("RSA验证失败");
            }
        }
        return respon;
    }


    public SysRespon QuerySign( SysDept dept) throws Exception {
        SysRespon respon=new SysRespon();
        JSONObject reqData = new JSONObject();
        reqData.put("mno",dept.getMno() );
        String req= SXFPaySign.getSXFPay(reqData);
        ///logger.debug("参数信息："+req);
        System.out.println("req:" + req);
        //此处不要改变reqData里面值的顺序用LinkedHashMap
        HashMap reqMap = JSON.parseObject(req, LinkedHashMap.class, Feature.OrderedField);
        //组装加密串
        String signContent = RSASignature.getOrderContent(reqMap);
        System.out.println("拼接后的参数：" + signContent);
        //logger.debug("拼接后的参数："+signContent);
        //sign
        String sign = RSASignature.encryptBASE64(RSASignature.sign(signContent, SXFPaySign.privateKey));
        System.out.println("============签名:" + sign);
        reqMap.put("sign", sign);
        String reqStr = JSON.toJSONString(reqMap);
        System.out.println("请求参数:" + reqMap);
        System.out.println("请求参数:" + reqStr);
        //调用第三方接口地址
        String url = "https://openapi.suixingpay.com/merchant/sign/querySignContract";//生产地址
        String resultJson = HttpUtils.connectPostUrl(url, reqStr);
        System.out.println("返回信息：" + resultJson);
        //不要对reqData排序 所以用LinkedHashMap
        HashMap<String, Object> result = JSON.parseObject(resultJson, LinkedHashMap.class, Feature.OrderedField);
        if ("0000".equals(result.get("code"))) {
            //验签
            String signResult = result.get("sign").toString();
            result.remove("sign");
            String resultStr = RSASignature.getOrderContent(result);
            System.out.println("resultStr: " + resultStr);
            //sign
            String resultSign = RSASignature.encryptBASE64(RSASignature.sign(signContent, SXFPaySign.privateKey));
            System.out.println("resultSign: " + resultSign);
            //组装加密串
            if (RSASignature.doCheck(resultStr, signResult, SXFPaySign.sxfPublic)) {
                System.out.println("===================验签成功==============");
                //
                if(result.containsKey("respData")){
                    HashMap<String, Object> result1 = JSON.parseObject(result.get("respData")+"", LinkedHashMap.class, Feature.OrderedField);
                    if("0000".equals(result1.get("bizCode"))){
                        respon.setResponCode("0000");
                        respon.setResponMessage(result1.get("signResult")+"");
                        System.out.println(result1.get("signResult"));
                        return respon ;
                    }else {
                        respon.setResponCode(result1.get("bizCode") + "");
                        respon.setResponMessage(result1.get("bizMsg") + "");
                    }
                    //判断 bizCode bizCode =="0000" 则业务成功
                }else {
                    respon.setResponCode("0004");
                    respon.setResponMessage(result.get("msg") + "");
                }

            }else {
                respon.setResponCode("0002");
                respon.setResponMessage("RSA验证失败");
            }
        }
        return respon;
    }


    public SysRespon setMnoArray( SysDept dept) throws Exception {
        SysRespon respon=new SysRespon();
        JSONObject reqData = new JSONObject();
        reqData.put("mno",dept.getMno() );
        reqData.put("mnoArray",dept.getMnoArray() );
        String req= SXFPaySign.getSXFPay(reqData);
        ///logger.debug("参数信息："+req);
        System.out.println("req:" + req);
        //此处不要改变reqData里面值的顺序用LinkedHashMap
        HashMap reqMap = JSON.parseObject(req, LinkedHashMap.class, Feature.OrderedField);
        //组装加密串
        String signContent = RSASignature.getOrderContent(reqMap);
        System.out.println("拼接后的参数：" + signContent);
        //logger.debug("拼接后的参数："+signContent);
        //sign
        String sign = RSASignature.encryptBASE64(RSASignature.sign(signContent, SXFPaySign.privateKey));
        System.out.println("============签名:" + sign);
        reqMap.put("sign", sign);
        String reqStr = JSON.toJSONString(reqMap);
        System.out.println("请求参数:" + reqMap);
        System.out.println("请求参数:" + reqStr);
        //调用第三方接口地址
        String url = "https://openapi.suixingpay.com/query/ledger/setMnoArray";//生产地址
        String resultJson = HttpUtils.connectPostUrl(url, reqStr);
        System.out.println("返回信息：" + resultJson);
        //不要对reqData排序 所以用LinkedHashMap
        HashMap<String, Object> result = JSON.parseObject(resultJson, LinkedHashMap.class, Feature.OrderedField);
        if ("0000".equals(result.get("code"))) {
            //验签
            String signResult = result.get("sign").toString();
            result.remove("sign");
            String resultStr = RSASignature.getOrderContent(result);
            System.out.println("resultStr: " + resultStr);
            //sign
            String resultSign = RSASignature.encryptBASE64(RSASignature.sign(signContent, SXFPaySign.privateKey));
            System.out.println("resultSign: " + resultSign);
            //组装加密串
            if (RSASignature.doCheck(resultStr, signResult, SXFPaySign.sxfPublic)) {
                System.out.println("===================验签成功==============");
                //
                if(result.containsKey("respData")){
                    HashMap<String, Object> result1 = JSON.parseObject(result.get("respData")+"", LinkedHashMap.class, Feature.OrderedField);
                    if("0000".equals(result1.get("bizCode"))){
                        respon.setResponCode("0000");
                        respon.setResponMessage("签约成功");
                        System.out.println(result1.get("signResult"));
                        return respon;
                    }else {
                        respon.setResponCode(result1.get("bizCode") + "");
                        respon.setResponMessage(result1.get("bizMsg") + "");
                    }
                    //判断 bizCode bizCode =="0000" 则业务成功
                }else {
                respon.setResponCode("0004");
                respon.setResponMessage(result.get("msg")+"");
                }
            }
            else {
                respon.setResponCode("0002");
                respon.setResponMessage("RSA验证失败");
            }
        }
        return respon;
    }

}
